package com.calvin.study.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Function;

import org.apache.commons.lang3.StringUtils;


//异步任务的串行执行。
public class SerializableTest extends BaseThreadPoolExecutor {
	
	public static void main(String[] args) {
		try {
			System.out.println("main ... start");
			//thenApplyTest1();
			//thenApplyTest2();
			thenApplyTest3();
			System.out.println("main ... end");
		} catch (Exception e) {
		}
	}


	public static void thenApplyTest3() throws InterruptedException, ExecutionException {
		CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
			// 业务执行 模拟生成订单
			Order order = getInsatance();
			// 业务执行成功返回值
			return order.getOrderId() + "$" + order.getPrice() + "$" + order.getCount() + "$" + order.getTotalPrice();
		}, executor).thenApplyAsync(new Function<String, String>() {
			// 获取上一步的执行结果,模拟执行扣减库存业务，并返回处理结果
			public String apply(String res) {
				System.out.println(res);
				int inventory = 100;
				String orderId = null;
				if (StringUtils.isNotBlank(res)) {
					String count = res.substring(StringUtils.ordinalIndexOf(res, "$", 2) + 1,
							StringUtils.ordinalIndexOf(res, "$", 3));
					orderId = res.substring(0, res.indexOf("$"));

					inventory = inventory - Integer.parseInt(count);
					return "[" + orderId + "]，扣减库存成功，库存剩余量：" + inventory;
				}
				return "[" + orderId + "],扣减库存失败";
			}
		}, executor);
		System.out.println("处理结果：" + future.get());
	}

	public static void thenApplyTest2() throws InterruptedException, ExecutionException {
		CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
			// 业务执行 模拟生成订单
			Order order = getInsatance();
			// 业务执行成功返回值
			return order.getOrderId() + "$" + order.getPrice() + "$" + order.getCount() + "$" + order.getTotalPrice();
		}, executor).thenAcceptAsync(new Consumer<String>() {
			@Override
			public void accept(String orderInfo) {
				// 获取上一步的执行结果，处理业务，无返回值
				System.out.println("订单信息：" + orderInfo);
			}
		}, executor);
		System.out.println(future.get());
	}

	public static void thenApplyTest1() throws InterruptedException, ExecutionException {
		CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
			// 业务执行 模拟生成订单
			Order order = getInsatance();
			// 业务执行成功返回值
			return order.getOrderId() + "$" + order.getPrice() + "$" + order.getCount() + "$" + order.getTotalPrice();
		}, executor).thenRunAsync(() -> {
			// 无法获取任务的上一步执行结果
			System.out.println("扣减库存开始");
		}, executor);
		
		System.out.println("线程返回结果：" + future.get());
	}

}
